package be.phl.obstacleapp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Files.FileColumns;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import be.phl.model.DBAdapterScreening;

public class ScreeningitemGalleryFragment extends Fragment {

	private Uri mUriPicTaken;

	private static final String TAG = "ScreeningitemGalleryFragment";
	// variable for selection intent
	private final int PICKER = 100;
	// adapter for gallery view
	private PicAdapter imgAdapt;
	// gallery object
	private Gallery picGallery;
	// image view for larger display
	private ImageView picView;
	// array to store bitmaps to display
	private List<PictureItem> imageBitmaps;

	public Uri getmUriPicTaken() {
		return mUriPicTaken;
	}

	public void setmUriPicTaken(Uri mUriPicTaken) {
		this.mUriPicTaken = mUriPicTaken;
	}

	public int getPICKER() {
		return PICKER;
	}

	public PicAdapter getImgAdapt() {
		return imgAdapt;
	}

	public Gallery getPicGallery() {
		return picGallery;
	}

	public ImageView getPicView() {
		return picView;
	}

	public List<PictureItem> getImageBitmaps() {
		return imageBitmaps;
	}

	public void setImageBitmaps(List<PictureItem> imageBitmaps) {
		this.imageBitmaps = imageBitmaps;
	}
	
	/**
	 * instantiate the interactive gallery
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		/*
		 * When the user clicks a thumbnail in the gallery it is displayed at
		 * larger size
		 */

		// call superclass method and set main content view
		super.onActivityCreated(savedInstanceState);

		// get the large image view
		picView = (ImageView) getActivity().findViewById(R.id.picture);

		// get the gallery view
		picGallery = (Gallery) getActivity().findViewById(R.id.gallery);

		// create a new adapter
		imgAdapt = new PicAdapter(getActivity());
		// set the gallery adapter
		picGallery.setAdapter(imgAdapt);

		// set long click listener for each gallery thumbnail item
		picGallery.setOnItemLongClickListener(new OnItemLongClickListener() {
			// handle long clicks
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View v,
					final int position, long id) {
				// delete the selected image

				new AlertDialog.Builder(getActivity())
						.setTitle("Wilt u de foto verwijderen?")
						.setPositiveButton(R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// delete picture
										PictureItem selected = imageBitmaps
												.get(position);
										// read the file given from the path
										File pictureFile = new File(selected
												.getPath());
										pictureFile.delete();
										DBAdapterScreening db = new DBAdapterScreening(
												getActivity());
										db.open();
										db.deletePictureItem(selected.getId());
										db.close();
										// remove the bitmap from de adapterlist
										// en notify change
										imageBitmaps.remove(position);
										imgAdapt.notifyDataSetChanged();
										picView.setImageBitmap(null);
									}
								})
						.setNegativeButton(R.string.cancel,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// User cancelled the dialog

									}
								}).show();

				return true;
			}
		});


		// set the click listener for each item in the thumbnail gallery
		picGallery.setOnItemClickListener(new OnItemClickListener() {
			// handle clicks
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				// set the larger image view to display
				// the chosen bitmap calling method of adapter class
				picView.setImageBitmap(imgAdapt.getPic(position).getImage());
			}
		});

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(
				R.layout.fragment_screeningitem_gallery, container, false);

		return rootView;

	}

	/**
	 * Base Adapter subclass creates Gallery view - provides method for adding
	 * new images from user selection - provides method to return bitmaps from
	 * array
	 * 
	 */
	public class PicAdapter extends BaseAdapter {

		// use the default gallery background image
		int defaultItemBackground;

		// gallery context
		private Context galleryContext;

		// placeholder bitmap for empty spaces in gallery
		Bitmap placeholder;

		// constructor
		public PicAdapter(Context c) {

			// instantiate context
			galleryContext = c;

			// get the styling attributes - use default Andorid system resources
			TypedArray styleAttrs = galleryContext
					.obtainStyledAttributes(R.styleable.PicGallery);
			// get the background resource
			defaultItemBackground = styleAttrs.getResourceId(
					R.styleable.PicGallery_android_galleryItemBackground, 0);
			// recycle attributes
			styleAttrs.recycle();
		}

		// BaseAdapter methods

		// return number of data items i.e. bitmap images
		@Override
		public int getCount() {
			return imageBitmaps.size();
		}

		// return item at specified position
		@Override
		public Object getItem(int position) {
			return position;
		}

		// return item ID at specified position
		@Override
		public long getItemId(int position) {
			return position;
		}

		// get view specifies layout and display options for each thumbnail in
		// the gallery
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			// create the view
			ImageView imageView = new ImageView(galleryContext);
			// specify the bitmap at this position in the array
			imageView.setImageBitmap(imageBitmaps.get(position).getImage());
			// set layout options
			imageView.setLayoutParams(new Gallery.LayoutParams(200,
					LayoutParams.MATCH_PARENT));
			// scale type within view area
			imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			// set default gallery item background
			imageView.setBackgroundResource(defaultItemBackground);
			// return the view
			return imageView;
		}

		// custom methods for this app

		// helper method to add a bitmap to the gallery when the user chooses
		// one
		public void addPic(PictureItem newPic) {
			// set at currently selected index
			imageBitmaps.add(newPic);
		}

		// return bitmap at specified position for larger display
		public PictureItem getPic(int posn) {
			// return bitmap at posn index
			return imageBitmaps.get(posn);
		}
	}

	/** Create a File for saving an image */
	public File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "Obstacle");
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.
		

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("Obstacle", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile;
		if (type == FileColumns.MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else {
			return null;
		}
		return mediaFile;
	}

	/**
	 * helper class to store the bitmap data
	 * 
	 * @author krisdelanghe
	 * 
	 */
	public static class PictureItem {
		private Bitmap image;
		private int Id;
		private String path;

		public PictureItem(Bitmap image, int id, String path) {
			super();
			this.image = image;
			Id = id;
			this.path = path;
		}

		public Bitmap getImage() {
			return image;
		}

		public void setImage(Bitmap image) {
			this.image = image;
		}

		public int getId() {
			return Id;
		}

		public void setId(int id) {
			Id = id;
		}

		public String getPath() {
			return path;
		}

		public void setPath(String path) {
			this.path = path;
		}
	}
}
